package net.chrone.quickpayapi.service.impl;

import java.util.Date;
import java.util.List;

import net.chrone.quickpayapi.mapper.MerchantMapper;
import net.chrone.quickpayapi.model.Merchant;
import net.chrone.quickpayapi.model.MerchantExample;
import net.chrone.quickpayapi.model.MerchantExample.Criteria;
import net.chrone.quickpayapi.model.PmsBankInf;
import net.chrone.quickpayapi.service.MccService;
import net.chrone.quickpayapi.service.MerchantService;
import net.chrone.quickpayapi.service.PmsBankInfService;
import net.chrone.quickpayapi.service.SeqService;
import net.chrone.quickpayapi.util.Constant;
import net.chrone.quickpayapi.util.SdkUtil;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service("merchantService")
public class MerchantServiceImpl implements MerchantService {
	
	private  final Logger logger = Logger.getLogger(getClass());
	
	@Autowired
	private SeqService seqService;
	@Autowired
	private MerchantMapper merchantMapper;
	@Autowired
	private PmsBankInfService pmsBankInfService;
	@Autowired
	private MccService mccService;

	@Override
	public Merchant regist(Merchant merchant) {
		PmsBankInf pmsBankInf = pmsBankInfService.find(merchant.getPmsBankNo());
//		merchant.setMchntId(seqService.updateAndGetSequence("mchntId", 8));
		String mchntId = mccService.getMerchantId();
		if(StringUtils.isEmpty(mchntId)){
			logger.debug("未找到商户mcc值,注册失败...");
			return null;
		}
		merchant.setMchntId(mchntId);
		merchant.setAccountSt(Constant.MCHNT_ST_AUDIT_PASS);//库贝账户状态,未注册
		merchant.setCityCd(pmsBankInf.getCityCd());
		merchant.setRegistDt(SdkUtil.formatDate(new Date(), "yyyyMMdd"));
		merchant.setFeeRate(0.0060d);
		merchant.setRowCrtTs(new Date());
		int i = merchantMapper.insertSelective(merchant);
		if(1==i){
			return merchant;
		}
		return null;
	}

	@Override
	public Merchant find(String orgId, String account) {
		MerchantExample example = new MerchantExample();
		Criteria criteria = example.createCriteria();
		criteria.andOrgIdEqualTo(orgId);
		criteria.andAccountEqualTo(account);
		List<Merchant> merchants = merchantMapper.selectByExample(example);
		if(merchants!=null&&merchants.size()>0){
			return merchants.get(0);
		}
		return null;
	}

	@Override
	public int update(Merchant merchant) {
		return merchantMapper.updateByPrimaryKeySelective(merchant);
	}

	@Override
	public int updateByExample(Merchant merchant) {
		MerchantExample example = new MerchantExample();
		Criteria criteria = example.createCriteria();
		criteria.andOrgIdEqualTo(merchant.getOrgId());
		criteria.andAccountEqualTo(merchant.getAccount());
		return merchantMapper.updateByExampleSelective(merchant, example);
	}


}
